package com.kongjs.application.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kongjs.common.mybatis.tenant.TenantContextHolder;
import com.kongjs.common.mybatis.user.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = UserContextHolder.getUserId();

        this.strictInsertFill(metaObject, "enabled", Integer.class, 1);
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());

        if (StringUtils.hasText(tenantId)) {
            this.strictInsertFill(metaObject, "tenantId", Long.class, Long.valueOf(tenantId));
        }
        if (StringUtils.hasText(userId)) {
            this.strictInsertFill(metaObject, "createUserId", Long.class, Long.valueOf(userId));
            this.strictInsertFill(metaObject, "updateUserId", Long.class, Long.valueOf(userId));
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = UserContextHolder.getUserId();
        this.strictUpdateFill(metaObject, "updateDate", LocalDateTime.class, LocalDateTime.now());
        if (StringUtils.hasText(userId)) {
            this.strictUpdateFill(metaObject, "updateUserId", Long.class, Long.valueOf(userId));
        }
    }
}
